package com.niu.business.utils.redisUtils;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static java.lang.annotation.ElementType.PARAMETER;

@Component
@NoArgsConstructor
@AllArgsConstructor
public class RedisUtils {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 指定缓存的key失效时间
     * @param key redis key
     * @param time time
     * @return
     */
    public boolean expire(String key,long time){
        try {
            if (time>0){
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入
     * @param key redis key
     * @param value object
     * @return
     */
    public boolean setKey(String key,Object value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;

        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 普通缓存获取
     * @param key redis key
     * @return
     */
    public Object getKey(String key){
      return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存删除
     * @param keys redis keys
     */
    @SuppressWarnings("PARAMETER")
    public void delKey(String ... keys){
        if (keys != null && keys.length > 0){
            if (keys.length == 1){
                redisTemplate.delete(keys[0]);
            }else {
                redisTemplate.delete(Arrays.asList(keys));
            }
        }
    }
}
